﻿<template>
  <div class="receipts-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>采购入库</h3>
          <div class="header-actions">
            <ExportButton 
              :data="tableData" 
              :columns="exportColumns" 
              filename="采购入库"
              data-type="receipts"
              @export="handleExport"
            />
            <el-button type="primary" @click="showAddDialog">
              <el-icon><Plus /></el-icon>
              新建入库
            </el-button>
          </div>
        </div>
      </template>

      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="入库单号">
            <el-input v-model="searchForm.receiptNo" placeholder="请输入入库单号" clearable />
          </el-form-item>
          <el-form-item label="采购订单">
            <el-select v-model="searchForm.purchaseOrderId" placeholder="请选择采购订单" clearable>
              <el-option 
                v-for="order in purchaseOrders" 
                :key="order.id" 
                :label="order.orderNo" 
                :value="order.id" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="供应商">
            <el-select v-model="searchForm.supplierId" placeholder="请选择供应商" clearable>
              <el-option 
                v-for="supplier in suppliers" 
                :key="supplier.id" 
                :label="supplier.name" 
                :value="supplier.id" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="待入库" value="待入库" />
              <el-option label="部分入库" value="部分入库" />
              <el-option label="已完成" value="已完成" />
            </el-select>
          </el-form-item>
          <el-form-item label="入库时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="receiptNo" label="入库单号" width="150" />
        <el-table-column prop="purchaseOrderNo" label="采购订单" width="150" />
        <el-table-column prop="supplierName" label="供应商" width="150" />
        <el-table-column prop="totalAmount" label="入库金额" width="120">
          <template #default="{ row }">
            ¥{{ row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="warehouse" label="仓库" width="120" />
        <el-table-column prop="operator" label="操作员" width="100" />
        <el-table-column prop="receiptTime" label="入库时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button 
              v-if="row.status === '待入库'" 
              type="success" 
              size="small" 
              @click="handleReceipt(row)"
            >
              确认入库
            </el-button>
            <el-button 
              v-if="row.status === '待入库'" 
              type="warning" 
              size="small" 
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="1000px"
      @close="handleDialogClose"
    >
      <el-form
        ref="receiptFormRef"
        :model="receiptForm"
        :rules="receiptRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库单号" prop="receiptNo">
              <el-input v-model="receiptForm.receiptNo" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购订单" prop="purchaseOrderId">
              <el-select v-model="receiptForm.purchaseOrderId" placeholder="请选择采购订单" style="width: 100%" @change="handleOrderChange">
                <el-option 
                  v-for="order in purchaseOrders" 
                  :key="order.id" 
                  :label="order.orderNo" 
                  :value="order.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierName">
              <el-input v-model="receiptForm.supplierName" placeholder="自动填充" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库" prop="warehouse">
              <el-select v-model="receiptForm.warehouse" placeholder="请选择仓库" style="width: 100%">
                <el-option label="主仓库" value="主仓库" />
                <el-option label="分仓库A" value="分仓库A" />
                <el-option label="分仓库B" value="分仓库B" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="操作员" prop="operator">
              <el-input v-model="receiptForm.operator" placeholder="请输入操作员" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库时间" prop="receiptTime">
              <el-date-picker
                v-model="receiptForm.receiptTime"
                type="datetime"
                placeholder="请选择入库时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="receiptForm.remark" 
            type="textarea" 
            :rows="2"
            placeholder="请输入备注信息" 
          />
        </el-form-item>

        <el-form-item label="商品明细">
          <div class="product-list">
            <el-table :data="receiptForm.products" border>
              <el-table-column prop="productCode" label="商品编码" width="120" />
              <el-table-column prop="productName" label="商品名称" width="200" />
              <el-table-column prop="specification" label="规格" width="150" />
              <el-table-column prop="unit" label="单位" width="80" />
              <el-table-column prop="orderQuantity" label="订单数量" width="100" />
              <el-table-column prop="receivedQuantity" label="已入库数量" width="120" />
              <el-table-column prop="receiptQuantity" label="本次入库" width="120">
                <template #default="{ row, $index }">
                  <el-input-number 
                    v-model="row.receiptQuantity" 
                    :min="0" 
                    :max="row.orderQuantity - row.receivedQuantity"
                    style="width: 100%"
                    @change="calculateAmount"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="unitPrice" label="单价" width="100">
                <template #default="{ row }">
                  ¥{{ row.unitPrice.toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column prop="amount" label="金额" width="100">
                <template #default="{ row }">
                  ¥{{ (row.receiptQuantity * row.unitPrice).toFixed(2) }}
                </template>
              </el-table-column>
            </el-table>
            <div class="total-amount">
              <span>入库总额：<strong>¥{{ receiptForm.totalAmount.toFixed(2) }}</strong></span>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="viewDialogVisible"
      title="入库详情"
      width="800px"
    >
      <div v-if="currentReceipt">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="入库单号">{{ currentReceipt.receiptNo }}</el-descriptions-item>
          <el-descriptions-item label="采购订单">{{ currentReceipt.purchaseOrderNo }}</el-descriptions-item>
          <el-descriptions-item label="供应商">{{ currentReceipt.supplierName }}</el-descriptions-item>
          <el-descriptions-item label="仓库">{{ currentReceipt.warehouse }}</el-descriptions-item>
          <el-descriptions-item label="入库金额">¥{{ currentReceipt.totalAmount.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentReceipt.status)">{{ currentReceipt.status }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="操作员">{{ currentReceipt.operator }}</el-descriptions-item>
          <el-descriptions-item label="入库时间">{{ currentReceipt.receiptTime }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ currentReceipt.remark || '-' }}</el-descriptions-item>
        </el-descriptions>

        <el-divider>商品明细</el-divider>
        <el-table :data="currentReceipt.products" border>
          <el-table-column prop="productCode" label="商品编码" width="120" />
          <el-table-column prop="productName" label="商品名称" width="200" />
          <el-table-column prop="specification" label="规格" width="150" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="orderQuantity" label="订单数量" width="100" />
          <el-table-column prop="receivedQuantity" label="已入库数量" width="120" />
          <el-table-column prop="receiptQuantity" label="本次入库" width="120" />
          <el-table-column prop="unitPrice" label="单价" width="100">
            <template #default="{ row }">
              ¥{{ row.unitPrice.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="金额" width="100">
            <template #default="{ row }">
              ¥{{ (row.receiptQuantity * row.unitPrice).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete, View } from '@element-plus/icons-vue'
import ExportButton from '@/components/common/ExportButton.vue'
import { getDefaultColumns } from '@/utils/export'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const submitLoading = ref(false)
const receiptFormRef = ref()

// 搜索表单
const searchForm = reactive({
  receiptNo: '',
  purchaseOrderId: '',
  supplierId: '',
  status: '',
  dateRange: []
})

// 入库表单
const receiptForm = reactive({
  id: null,
  receiptNo: '',
  purchaseOrderId: '',
  purchaseOrderNo: '',
  supplierName: '',
  warehouse: '',
  operator: '',
  receiptTime: '',
  totalAmount: 0,
  remark: '',
  products: []
})

// 表单验证规则
const receiptRules = {
  purchaseOrderId: [
    { required: true, message: '请选择采购订单', trigger: 'change' }
  ],
  warehouse: [
    { required: true, message: '请选择仓库', trigger: 'change' }
  ],
  operator: [
    { required: true, message: '请输入操作员', trigger: 'blur' }
  ],
  receiptTime: [
    { required: true, message: '请选择入库时间', trigger: 'change' }
  ]
}

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 采购订单数据
const purchaseOrders = ref([
  { id: 1, orderNo: 'PO20240115001', supplierName: '苹果供应商', status: '已确认' },
  { id: 2, orderNo: 'PO20240115002', supplierName: '耐克供应商', status: '已确认' }
])

// 供应商数据
const suppliers = ref([
  { id: 1, name: '苹果供应商', code: 'S001' },
  { id: 2, name: '耐克供应商', code: 'S002' },
  { id: 3, name: '宜家供应商', code: 'S003' }
])

// 表格数据
const tableData = ref([
  {
    id: 1,
    receiptNo: 'RI20240115001',
    purchaseOrderId: 1,
    purchaseOrderNo: 'PO20240115001',
    supplierName: '苹果供应商',
    totalAmount: 25000,
    status: '已完成',
    warehouse: '主仓库',
    operator: '张三',
    receiptTime: '2024-01-15 14:30:00',
    remark: '正常入库',
    products: [
      {
        productCode: 'P001',
        productName: 'iPhone 15',
        specification: '128GB 黑色',
        unit: '台',
        orderQuantity: 5,
        receivedQuantity: 5,
        receiptQuantity: 5,
        unitPrice: 5000
      }
    ]
  },
  {
    id: 2,
    receiptNo: 'RI20240115002',
    purchaseOrderId: 2,
    purchaseOrderNo: 'PO20240115002',
    supplierName: '耐克供应商',
    totalAmount: 12000,
    status: '待入库',
    warehouse: '分仓库A',
    operator: '李四',
    receiptTime: '',
    remark: '',
    products: [
      {
        productCode: 'P003',
        productName: 'Nike运动鞋',
        specification: '42码 白色',
        unit: '双',
        orderQuantity: 30,
        receivedQuantity: 0,
        receiptQuantity: 0,
        unitPrice: 400
      }
    ]
  }
])

const currentReceipt = ref(null)

// 导出列配置
const exportColumns = [
  { key: 'id', label: 'ID', type: 'number' },
  { key: 'receiptNo', label: '入库单号' },
  { key: 'purchaseOrderNo', label: '采购订单' },
  { key: 'supplierName', label: '供应商' },
  { key: 'totalAmount', label: '入库金额', type: 'currency' },
  { key: 'status', label: '状态' },
  { key: 'warehouse', label: '仓库' },
  { key: 'operator', label: '操作员' },
  { key: 'receiptTime', label: '入库时间', type: 'date' }
]

// 计算属性
const isEdit = computed(() => !!receiptForm.id)
const dialogTitle = computed(() => isEdit.value ? '编辑入库' : '新建入库')

// 方法
const loadData = () => {
  loading.value = true
  setTimeout(() => {
    pagination.total = tableData.value.length
    loading.value = false
  }, 500)
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    receiptNo: '',
    purchaseOrderId: '',
    supplierId: '',
    status: '',
    dateRange: []
  })
  handleSearch()
}

const showAddDialog = () => {
  dialogVisible.value = true
  resetForm()
  generateReceiptNo()
}

const handleEdit = (row) => {
  dialogVisible.value = true
  Object.assign(receiptForm, { ...row })
}

const handleView = (row) => {
  currentReceipt.value = row
  viewDialogVisible.value = true
}

const handleReceipt = async (row) => {
  try {
    await ElMessageBox.confirm('确定要确认入库吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value[index].status = '已完成'
      tableData.value[index].receiptTime = new Date().toLocaleString()
      ElMessage.success('入库确认成功')
      loadData()
    }
  } catch {
    // 用户取消操作
  }
}

const handleOrderChange = (orderId) => {
  const order = purchaseOrders.value.find(o => o.id === orderId)
  if (order) {
    receiptForm.purchaseOrderNo = order.orderNo
    receiptForm.supplierName = order.supplierName
    
    // 模拟加载订单商品明细
    receiptForm.products = [
      {
        productCode: 'P001',
        productName: 'iPhone 15',
        specification: '128GB 黑色',
        unit: '台',
        orderQuantity: 5,
        receivedQuantity: 0,
        receiptQuantity: 0,
        unitPrice: 5000
      }
    ]
  }
}

const calculateAmount = () => {
  receiptForm.totalAmount = receiptForm.products.reduce((total, product) => {
    return total + (product.receiptQuantity * product.unitPrice)
  }, 0)
}

const generateReceiptNo = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const random = String(Math.floor(Math.random() * 1000)).padStart(3, '0')
  receiptForm.receiptNo = `RI${year}${month}${day}${random}`
}

const getStatusType = (status) => {
  const statusMap = {
    '待入库': 'warning',
    '部分入库': 'info',
    '已完成': 'success'
  }
  return statusMap[status] || 'info'
}

const handleSubmit = async () => {
  if (!receiptFormRef.value) return

  try {
    await receiptFormRef.value.validate()
    
    if (receiptForm.products.length === 0) {
      ElMessage.warning('请选择采购订单')
      return
    }

    submitLoading.value = true

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    if (isEdit.value) {
      // 编辑入库
      const index = tableData.value.findIndex(item => item.id === receiptForm.id)
      if (index > -1) {
        tableData.value[index] = { ...receiptForm }
      }
      ElMessage.success('编辑成功')
    } else {
      // 新增入库
      const newReceipt = {
        ...receiptForm,
        id: Date.now(),
        status: '待入库',
        receiptTime: receiptForm.receiptTime || new Date().toLocaleString()
      }
      tableData.value.unshift(newReceipt)
      ElMessage.success('新建成功')
    }

    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  resetForm()
}

const resetForm = () => {
  Object.assign(receiptForm, {
    id: null,
    receiptNo: '',
    purchaseOrderId: '',
    purchaseOrderNo: '',
    supplierName: '',
    warehouse: '',
    operator: '',
    receiptTime: '',
    totalAmount: 0,
    remark: '',
    products: []
  })
  receiptFormRef.value?.clearValidate()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

const handleExport = (exportInfo) => {
  console.log('导出完成:', exportInfo)
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.receipts-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.product-list {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

.total-amount {
  margin-top: 10px;
  text-align: right;
  font-size: 16px;
  color: #e6a23c;
}
</style>
